<script setup lang="ts">
import { onMounted, ref } from 'vue'
import ParameterList from './YkParaList.vue'
import systemdemo from '@/components/ts/systemdemo'
import { df_from_excel } from '@/components/ts/EtPandas'
import { trim_na_element } from '@/components/ts/pandas'
import { handleGeneratePoints } from '@/components/ts/测点清单'
import { load_curves_sheet, get_correct_title } from '@/components/ts/修正曲线'
import { handleCalculate } from '@/components/ts/联合循环表计算'
import { calSteamTurbine, set_leakage_title, load_leakage_sheet } from '@/components/ts/汽机计算'
import { useCCPPStore, allCorrectParas, allLeakageParas } from '@/store'
import AdvancedSettings from './AdvancedSettings.vue'
import { storeToRefs } from 'pinia'
import PowerChoice from './PowerSettings/PowerChoice.vue'
import Util from '@/components/ts/util.js'

const store = useCCPPStore()

// 使用store中的变量替代原来的本地变量
const {
  unitTypes,
  gasFlowTypes,
  selectedGasFlowType,
  selectedUnitType,
  pulseToVolumeRatio,
  designLHV,
  designFlowRate,
  designFlowRateUnit,
  flowRateUnits,
  correct_paras,
  leakage_paras,
  logs,
  calTypes,
  calIndex,
  hasTCA,
  hasFGH,
  threePres,
  sp,
  leakageRegion,
  condensateConfig,
  hpConfig,
  mpConfig,
  lpConfig
} = storeToRefs(store)
const { printToTerm } = store

function transpose(matrix) {
  return matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]))
}

const init_curves_sheet = () => {
  // 读取现有的修正曲线工作表，判断行标题和项目生成的行标题是否相同，如果相同，则不做修改，如果不同，则删除现有的，创建新的标题
  const desired_title = trim_na_element(get_correct_title(correct_paras.value))
  if (systemdemo.exist_sheet('修正曲线')) {
    const df = df_from_excel('修正曲线', 1, 1, true, false)
    const now_title = trim_na_element(df.index)
    const titlesAreEqual = now_title.length === desired_title.length &&
      now_title.every((val, index) => val === desired_title[index])
    if (titlesAreEqual) {
      printToTerm(`当前修正曲线工作表已存在，标题相同，无需修改`)
    } else {
      systemdemo.clear_sheet('修正曲线')
      systemdemo.create_new_sheet('修正曲线', true)
      systemdemo.set_cells(1, 1, transpose([desired_title]))
    }
  } else {
    systemdemo.create_new_sheet('修正曲线', true)
    systemdemo.set_cells(1, 1, transpose([desired_title]))
  }

  systemdemo.auto_fit_columns()
}

/**
 * 一些额外的高级配置
 */
const showAdvancedSettings = ref(false)

const init_leakage_sheet = () => {
  set_leakage_title('漏汽')
}


// 组件初始化时加载配置
onMounted(() => {
  loadSettings()
})

const saveSettings = () => {
  // 创建settings对象
  const settings = {
    unitType: selectedUnitType.value,
    gasFlowType: selectedGasFlowType.value,
    pulseToVolumeRatio: pulseToVolumeRatio.value,
    designLHV: designLHV.value,
    designFlowRate: designFlowRate.value,
    designFlowRateUnit: designFlowRateUnit.value,
    calIndex: calIndex.value,
    hasTCA: hasTCA.value,
    hasFGH: hasFGH.value,
    threePres: threePres.value
  }

  // 将settings对象转换为JSON字符串并保存到工作表中
  try {
    // 确保pro_dat工作表存在
    systemdemo.create_new_sheet('pro_dat', false)
    // 将settings对象写入工作表A1单元格
    systemdemo.set_cell_value(1, 1, JSON.stringify(settings), 'pro_dat')
    // 将leakage_paras保存到A2单元格
    systemdemo.set_cell_value(2, 1, JSON.stringify(leakage_paras.value), 'pro_dat')
    // 将correct_paras保存到A3单元格
    systemdemo.set_cell_value(3, 1, JSON.stringify(correct_paras.value), 'pro_dat')
    console.log('设置已保存到工作表')
  } catch (error) {
    console.error('保存设置时出错:', error)
  }
}

// 从工作表加载配置
const loadSettings = () => {
  try {
    // 检查是否存在pro_dat工作表
    if (systemdemo.exist_sheet('pro_dat')) {
      // 如果存在，则读取其中的配置
      const settingsStr = systemdemo.get_cell_value(1, 1, 'pro_dat')
      if (settingsStr) {
        const settings = JSON.parse(settingsStr)
        // console.log(settings)
        // 恢复配置
        if (settings.unitType && unitTypes.value.includes(settings.unitType)) {
          // console.log(settings.unitType)
          selectedUnitType.value = settings.unitType
        }
        if (settings.gasFlowType && gasFlowTypes.value.includes(settings.gasFlowType)) {
          // console.log(settings.gasFlowType)
          selectedGasFlowType.value = settings.gasFlowType
        }
        if (settings.pulseToVolumeRatio) {
          pulseToVolumeRatio.value = settings.pulseToVolumeRatio
        }
        // 恢复新增的设计参数
        if (settings.designLHV !== undefined) {
          designLHV.value = settings.designLHV
        }
        if (settings.designFlowRate !== undefined) {
          designFlowRate.value = settings.designFlowRate
        }
        if (settings.designFlowRateUnit && flowRateUnits.value.includes(settings.designFlowRateUnit)) {
          designFlowRateUnit.value = settings.designFlowRateUnit
        }
        // 恢复计算类型
        if (settings.calIndex && Array.isArray(settings.calIndex)) {
          calIndex.value = settings.calIndex
        }
        // 恢复机组配置选项
        if (settings.hasTCA !== undefined) {
          hasTCA.value = settings.hasTCA
        }
        if (settings.hasFGH !== undefined) {
          hasFGH.value = settings.hasFGH
        }
        if (settings.threePres !== undefined) {
          threePres.value = settings.threePres
        }
        // console.log("配置已从工作表加载");
      }

      // 从A2单元格加载leakageParas
      const leakageParasStr = systemdemo.get_cell_value(2, 1, 'pro_dat')
      if (leakageParasStr) {
        const leakageParas = JSON.parse(leakageParasStr)
        if (Array.isArray(leakageParas)) {
          leakage_paras.value = leakageParas
        }
      }

      // 从A3单元格加载correctParas
      const correctParasStr = systemdemo.get_cell_value(3, 1, 'pro_dat')
      if (correctParasStr) {
        const correctParas = JSON.parse(correctParasStr)
        if (Array.isArray(correctParas)) {
          correct_paras.value = correctParas
        }
      }

      // 从A10单元格加载高级配置
      const advancedSettingsStr = systemdemo.get_cell_value(10, 1, 'pro_dat')
      if (advancedSettingsStr) {
        const advancedSettings = JSON.parse(advancedSettingsStr)

        // 恢复高级配置
        if (advancedSettings.hpConfig) {
          Object.assign(hpConfig.value, advancedSettings.hpConfig)
        }
        if (advancedSettings.mpConfig) {
          Object.assign(mpConfig.value, advancedSettings.mpConfig)
        }
        if (advancedSettings.lpConfig) {
          Object.assign(lpConfig.value, advancedSettings.lpConfig)
        }
        if (advancedSettings.condensateConfig) {
          Object.assign(condensateConfig.value, advancedSettings.condensateConfig)
        }
      }

    }
  } catch (error) {
    console.error('加载配置时出错:', error)
    printToTerm(`加载配置时出错:${error}`)
  }
}

const ShowPowerChoice = () => {
  window.Application.ShowDialog(Util.GetUrlPath() + '/power-settings', '功率测点位置设置', 1000, 600, true)
}
</script>

<template>
  <div class="ccpp-container">
    <!-- 信息输入区域 -->
    <div class="input-section p-1">
      <!--  选择计算类型    -->
      <div class="flex items-center border-2 rounded mb-2" style="border-color: #00f100">
        <label class="input-label">计算类型:</label>
        <div class="checkbox-group flex flex-wrap gap-1">
          <label v-for="type in calTypes" :key="type" class="w-20 p-0 flex items-center">
            <input
              type="checkbox"
              :value="type"
              v-model="calIndex"
              class="checkbox-input"
            >
            <span>{{ type }}</span>
          </label>
        </div>
      </div>
      <!-- 顶部按钮区域 -->
      <div class="button-bar">
        <button @click="handleGeneratePoints" class="action-button">生成测点清单</button>
        <button @click="saveSettings" class="action-button">保存配置</button>
        <button @click="store.scanData" class="action-button">加载数据</button>
      </div>
      <!--  选择机组型式   -->
      <div class="input-group">
        <label class="input-label">机组型式:</label>
        <select v-model="selectedUnitType" class="input-select">
          <option v-for="type in unitTypes" :key="type" :value="type">
            {{ type }}
          </option>
        </select>
      </div>

      <div class="input-group">
        <label class="input-label">机组配置:</label>
        <div class="checkbox-group">
          <label class="checkbox-label">
            <input
              type="checkbox"
              v-model="hasTCA"
              class="checkbox-input"
            >
            <span>TCA</span>
          </label>
          <label class="checkbox-label">
            <input
              type="checkbox"
              v-model="hasFGH"
              class="checkbox-input"
            >
            <span>FGH</span>
          </label>
          <label class="checkbox-label">
            <input
              type="checkbox"
              v-model="threePres"
              class="checkbox-input"
            >
            <span>三压</span>
          </label>
        </div>
      </div>

      <div style="margin-top: 10px; background-color: #FFF0F0">
        <div class="input-group" style="margin-top: 10px;">
          <label class="input-label">天然气流量类型:</label>
          <select v-model="selectedGasFlowType" class="input-select">
            <option v-for="type in gasFlowTypes" :key="type" :value="type">
              {{ type }}
            </option>
          </select>
        </div>
        <div v-if="selectedGasFlowType === '涡轮流量计_脉冲计数'" class="input-group" style="margin-top: 10px;">
          <label class="input-label">脉冲数换算:</label>
          <input
            v-model="pulseToVolumeRatio"
            class="input-select"
            type="number"
            placeholder="" style="width: 100px;"
          >
          <span style="margin-left: 0; color: #666;">脉冲=1m³</span>
        </div>
      </div>
      <div class="input-group">
        <button @click="ShowPowerChoice" class="action-button">设置功率测量位置</button>
      </div>

      <!-- 添加设计天然气低位热值输入 -->
      <div style="margin-top: 10px; background-color: #F0FeF0">
        <label class="input-label">设计工况参数</label>
        <div class="input-group" style="margin-top: 10px;">
          <label class="input-label">天然气低位热值:</label>
          <input
            v-model="designLHV"
            class="input-select"
            type="number"
            placeholder="请输入天然气低位热值" style="width: 100px;"
          >
          <span style="margin-left: 5px; color: #666;">kJ/kg</span>
        </div>
        <!-- 添加设计天然气流量输入 -->
        <div class="input-group" style="margin-top: 10px;">
          <label class="input-label">天然气流量:</label>
          <input
            v-model="designFlowRate"
            class="input-select"
            type="number"
            placeholder="请输入天然气流量" style="width: 100px;"
          >
          <select v-model="designFlowRateUnit" class="input-select" style="width: 80px; margin-left: 5px;">
            <option v-for="unit in flowRateUnits" :key="unit" :value="unit">
              {{ unit }}
            </option>
          </select>
        </div>
      </div>

      <!-- 修正参数列表 -->
      <div class="input-group" style="margin-top: 10px; flex-direction: column; align-items: flex-start;">
        <ParameterList
          v-model="correct_paras"
          label="修正参数"
          :all-parameters="allCorrectParas as any"
        />
        <div class="button-row">
          <button @click="init_curves_sheet" class="small-button">生成【修正曲线】表</button>
          <button @click="load_curves_sheet()" class="small-button">加载【修正曲线】表</button>
        </div>
      </div>

      <div class="button-bar">
        <button @click="handleCalculate" class="action-button">联合循环计算</button>
      </div>
    </div>


    <div class="input-section" v-if="store.calIndex.includes('汽机')">
      <label class="input-label">汽机计算</label>
      <div class="input-group"
           style="margin-top: 10px; flex-direction: column; align-items: flex-start;">
        <ParameterList style="width: 100%"
                       v-model="leakage_paras"
                       label="漏气设置"
                       :all-parameters="allLeakageParas as any"
        />
        <div class="button-row">
          <button @click="init_leakage_sheet" class="small-button">生成【漏汽参数】表</button>
          <button @click="load_leakage_sheet()" class="small-button">加载【漏汽参数】表</button>
        </div>
      </div>
      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 这里可以放置计算表单、参数设置等内容 -->
        <span>yangke</span>
      </div>

      <div class="button-bar">
        <button @click="calSteamTurbine" class="action-button">汽轮机计算</button>
        <button @click="showAdvancedSettings = true" class="action-button">高级配置</button>
      </div>
    </div>
    <!-- 底部终端日志区域 -->
    <div class="terminal-container">
      <div class="terminal-header">
        <span>运行日志</span>
      </div>
      <div class="terminal-body">
        <div
          v-for="(log, index) in logs"
          :key="index"
          class="log-entry"
        >
          {{ log }}
        </div>
      </div>
    </div>

    <div class="button-row">
      <button @click="console.log(sp)" class="small-button">打印sp测点</button>
      <button @click="console.log(leakageRegion)" class="small-button">打印leakageRegion</button>
      <button @click="console.log(leakage_paras)" class="small-button">打印leakage_paras</button>
    </div>
  </div>

  <!-- 高级配置弹窗 -->
  <div v-if="showAdvancedSettings" class="dialog-overlay flex items-center w-full h-full"
       @click="showAdvancedSettings = false">
    <div class="rounded-lg shadow-md bg-white flex flex-col w-full h-full" @click.stop>
      <div class="p-4 border-b border-gray-200 w-full flex">
        <span class="text-base font-bold text-gray-700 flex-1">高级配置</span>
        <button class="bg-none border-none text-2xl cursor-pointer text-gray-400 p-0 w-6 h-6"
                @click="showAdvancedSettings = false">×
        </button>
      </div>
      <div class="dialog-content">
        <AdvancedSettings />
      </div>

    </div>
  </div>
</template>

<style scoped>
.ccpp-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
  box-sizing: border-box;
}

.input-section {
  margin-bottom: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.input-label {
  font-weight: bold;
  color: #333;
  min-width: 120px;
}

.checkbox-group {
  display: flex;
  gap: 15px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-weight: normal;
  color: #333;
}

.checkbox-input {
  width: 16px;
  height: 16px;
}

.input-select {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  font-size: 14px;
  width: 200px;
}

.button-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ddd;
}

.action-button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.button-row {
  display: flex;
  flex-direction: row;
  gap: 10px;
  flex-wrap: nowrap;
  white-space: nowrap;
}

.small-button {
  padding: 5px 5px;
  background-color: #3ab54a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
}

.action-button:hover {
  background-color: #66b1ff;
}

.main-content {
  flex: 1;
  margin-bottom: 20px;
  overflow: auto;
}

.terminal-container {
  display: flex;
  flex-direction: column;
  height: 300px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #1e1e1e;
}

.terminal-header {
  padding: 8px 12px;
  background-color: #2d2d2d;
  color: #fff;
  font-weight: bold;
  border-bottom: 1px solid #444;
}

.terminal-body {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  color: #ccc;
}

.log-entry {
  margin-bottom: 4px;
  line-height: 1.4;
}

.log-entry:last-child {
  margin-bottom: 0;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  flex: 1;
  padding: 0;
  overflow: auto;
  min-height: 300px;
}


</style>